package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.bo.ErpSellerStoreCommodityRankStatisticsBo;
import com.erp.gather.domain.vo.ErpSellerStoreCommodityRankStatisticsVo;
import com.erp.gather.mapper.ErpSellerStoreCommodityRankStatisticsMapper;
import com.erp.gather.mapper.ErpSellerStoreProductExpandMapper;
import com.erp.gather.mapper.ErpSellerStoreProductMapper;
import com.erp.gather.mapper.ErpSellerStoreProductSkuMapper;
import com.erp.gather.service.IErpSellerStoreCommodityRankStatisticsService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.ErpSellerStoreCommodityRankStatistics;
import com.ruoyi.gather.api.domain.ErpSellerStoreProduct;
import com.ruoyi.gather.api.domain.ErpSellerStoreProductExpand;
import com.ruoyi.gather.api.domain.ErpSellerStoreProductSku;
import com.ruoyi.gather.api.domain.dto.EvaluationProductDto;
import com.ruoyi.gather.api.domain.dto.ProductInfoModuleDto;
import com.ruoyi.order.api.RemoteEvaluationService;
import com.ruoyi.shop.api.RemoteSellerStorePriceTemplateService;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.shop.api.domain.ErpSellerStorePriceTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 店铺商品排行记录Service业务层处理
 *
 * @author erp
 * @date 2024-01-03
 */
@RequiredArgsConstructor
@Service
public class ErpSellerStoreCommodityRankStatisticsServiceImpl implements IErpSellerStoreCommodityRankStatisticsService {

    private final ErpSellerStoreCommodityRankStatisticsMapper baseMapper;
    private final ErpSellerStoreProductExpandMapper sellerStoreProductExpandMapper;
    private final ErpSellerStoreProductMapper erpSellerStoreProductMapper;
    private final RemoteSellerStorePriceTemplateService remoteSellerStorePriceTemplateService;
    
    private final RemoteEvaluationService remoteEvaluationService;
    private final RemoteSellerStoreService remoteSellerStoreService;

    /**
     * 查询店铺商品排行记录
     */
    @Override
    public ErpSellerStoreCommodityRankStatisticsVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询店铺商品排行记录列表
     */
    @Override
    public TableDataInfo<ErpSellerStoreCommodityRankStatisticsVo> queryPageList(ErpSellerStoreCommodityRankStatisticsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSellerStoreCommodityRankStatistics> lqw = buildQueryWrapper(bo);
        Page<ErpSellerStoreCommodityRankStatisticsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询店铺商品排行记录列表
     */
    @Override
    public List<ErpSellerStoreCommodityRankStatisticsVo> queryList(ErpSellerStoreCommodityRankStatisticsBo bo) {
        LambdaQueryWrapper<ErpSellerStoreCommodityRankStatistics> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSellerStoreCommodityRankStatistics> buildQueryWrapper(ErpSellerStoreCommodityRankStatisticsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerStoreCommodityRankStatistics> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getStoreId() != null, ErpSellerStoreCommodityRankStatistics::getStoreId, bo.getStoreId());
        lqw.eq(bo.getProductId() != null, ErpSellerStoreCommodityRankStatistics::getProductId, bo.getProductId());
        lqw.eq(StringUtils.isNotBlank(bo.getTimeFrame()), ErpSellerStoreCommodityRankStatistics::getTimeFrame, bo.getTimeFrame());
        lqw.eq(bo.getCategoryId() != null, ErpSellerStoreCommodityRankStatistics::getCategoryId, bo.getCategoryId());
        lqw.eq(bo.getRank() != null, ErpSellerStoreCommodityRankStatistics::getRank, bo.getRank());
        lqw.eq(bo.getTaxes() != null, ErpSellerStoreCommodityRankStatistics::getTaxes, bo.getTaxes());
        lqw.eq(bo.getProductPurchasingTips() != null, ErpSellerStoreCommodityRankStatistics::getProductPurchasingTips, bo.getProductPurchasingTips());
        lqw.eq(bo.getVisitors() != null, ErpSellerStoreCommodityRankStatistics::getVisitors, bo.getVisitors());
        lqw.eq(bo.getBuyersPaid() != null, ErpSellerStoreCommodityRankStatistics::getBuyersPaid, bo.getBuyersPaid());
        lqw.eq(bo.getOldBuyer() != null, ErpSellerStoreCommodityRankStatistics::getOldBuyer, bo.getOldBuyer());
        lqw.eq(bo.getWishlists() != null, ErpSellerStoreCommodityRankStatistics::getWishlists, bo.getWishlists());
        lqw.eq(bo.getPaidProductNumber() != null, ErpSellerStoreCommodityRankStatistics::getPaidProductNumber, bo.getPaidProductNumber());
        lqw.eq(bo.getClickRate() != null, ErpSellerStoreCommodityRankStatistics::getClickRate, bo.getClickRate());
        lqw.eq(bo.getPageViews() != null, ErpSellerStoreCommodityRankStatistics::getPageViews, bo.getPageViews());
        lqw.eq(bo.getCreatedOrdersGmv() != null, ErpSellerStoreCommodityRankStatistics::getCreatedOrdersGmv, bo.getCreatedOrdersGmv());
        lqw.eq(bo.getTransactionAmount() != null, ErpSellerStoreCommodityRankStatistics::getTransactionAmount, bo.getTransactionAmount());
        lqw.eq(bo.getAverageVisitorDuration() != null, ErpSellerStoreCommodityRankStatistics::getAverageVisitorDuration, bo.getAverageVisitorDuration());
        lqw.eq(bo.getOldVisitors() != null, ErpSellerStoreCommodityRankStatistics::getOldVisitors, bo.getOldVisitors());
        lqw.eq(bo.getNewBuyer() != null, ErpSellerStoreCommodityRankStatistics::getNewBuyer, bo.getNewBuyer());
        lqw.eq(bo.getPaidOrders() != null, ErpSellerStoreCommodityRankStatistics::getPaidOrders, bo.getPaidOrders());
        lqw.eq(bo.getNewVisitors() != null, ErpSellerStoreCommodityRankStatistics::getNewVisitors, bo.getNewVisitors());
        lqw.eq(bo.getExposure() != null, ErpSellerStoreCommodityRankStatistics::getExposure, bo.getExposure());
        lqw.eq(bo.getOrders() != null, ErpSellerStoreCommodityRankStatistics::getOrders, bo.getOrders());
        lqw.eq(bo.getOrderProductNumber() != null, ErpSellerStoreCommodityRankStatistics::getOrderProductNumber, bo.getOrderProductNumber());
        lqw.eq(bo.getCreatedBuyers() != null, ErpSellerStoreCommodityRankStatistics::getCreatedBuyers, bo.getCreatedBuyers());
        lqw.eq(bo.getRefundAmount() != null, ErpSellerStoreCommodityRankStatistics::getRefundAmount, bo.getRefundAmount());
        lqw.like(StringUtils.isNotBlank(bo.getCateLeafName()), ErpSellerStoreCommodityRankStatistics::getCateLeafName, bo.getCateLeafName());
        lqw.like(StringUtils.isNotBlank(bo.getCateLeafPathName()), ErpSellerStoreCommodityRankStatistics::getCateLeafPathName, bo.getCateLeafPathName());
        lqw.eq(bo.getRatioOfPageviewsToOrders() != null, ErpSellerStoreCommodityRankStatistics::getRatioOfPageviewsToOrders, bo.getRatioOfPageviewsToOrders());
        lqw.eq(bo.getConversionRate() != null, ErpSellerStoreCommodityRankStatistics::getConversionRate, bo.getConversionRate());
        lqw.eq(bo.getRevenuePerBuyer() != null, ErpSellerStoreCommodityRankStatistics::getRevenuePerBuyer, bo.getRevenuePerBuyer());
        lqw.eq(bo.getPaymentUnitPrice() != null, ErpSellerStoreCommodityRankStatistics::getPaymentUnitPrice, bo.getPaymentUnitPrice());
        lqw.eq(bo.getRevenuePerVisitor() != null, ErpSellerStoreCommodityRankStatistics::getRevenuePerVisitor, bo.getRevenuePerVisitor());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerStoreCommodityRankStatistics::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增店铺商品排行记录
     */
    @Override
    public Boolean insertByBo(ErpSellerStoreCommodityRankStatisticsBo bo) {
        ErpSellerStoreCommodityRankStatistics add = BeanUtil.toBean(bo, ErpSellerStoreCommodityRankStatistics.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改店铺商品排行记录
     */
    @Override
    public Boolean updateByBo(ErpSellerStoreCommodityRankStatisticsBo bo) {
        ErpSellerStoreCommodityRankStatistics update = BeanUtil.toBean(bo, ErpSellerStoreCommodityRankStatistics.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerStoreCommodityRankStatistics entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除店铺商品排行记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<ProductInfoModuleDto> getProductRankByStoreId(String outOrder, Integer productSource, Long storeId, Integer limit) {

        return baseMapper.getProductRankByStoreId(outOrder, productSource, storeId, limit);
    }

    @Override
    public List<Long> getProductsRankByPrimary(Long productId, Integer productSource, Integer productOut) {
        String tem = null;
        if (productSource == 0) {
            // 获取到商品的类目
            ErpSellerStoreProduct erpSellerStoreProduct = erpSellerStoreProductMapper.selectByAeId(productId);
            if (erpSellerStoreProduct != null) {
                Long categoryId = erpSellerStoreProduct.getCategoryId();
                if (categoryId != null) {
                    tem = categoryId.toString();
                    return baseMapper.getProductsRankByPrimary(productId, tem, productOut, productSource);
                }
            }
        }
        else if (productSource == 1){
            // 获取商品分组
            ErpSellerStoreProductExpand productExpand = sellerStoreProductExpandMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerStoreProductExpand>()
                            .eq(ErpSellerStoreProductExpand::getAeProductId, productId));
            if (productExpand != null) {
                Long groupId = productExpand.getGroupId();
                if (groupId != null) {
                    tem = groupId.toString();
                    return baseMapper.getProductsRankByPrimary(productId, tem, productOut, productSource);
                }
            }
        }
        else {
            // 全店铺
            return baseMapper.getProductsRankByPrimary(productId, tem, productOut, productSource);
        }

        return new ArrayList<>();
    }

    /**
     * 查询周期内的访客量
     * @param aeProductId
     * @param statisticalPeriod
     * @return
     */
    @Override
    public Integer selectVisitorsTotalsByTime(Long aeProductId, Integer statisticalPeriod){
        return baseMapper.selectVisitorsTotalsByTime(aeProductId, statisticalPeriod);
    }

    @Override
    public Boolean isOutOrder(Long productId) {
        Integer outOrder = baseMapper.isOutOrder(productId);
        if (outOrder == null)
            return false;
        return outOrder > 0;
    }

    @Override
    public List<EvaluationProductDto> getEvaluationProduct(Long storeId, List<String> shieldProductIds,String maxBig,String minBig) {
        // 根据cn码获取到所有店铺授权信息
        ErpSellerStoreEmpower compriseDeleteById = remoteSellerStoreService.getCompriseDeleteById(storeId);
        R<Object> storeEmpowerListByCnCode = remoteSellerStoreService.getStoreEmpowerListByCnCode(compriseDeleteById.getStoreUserName());
        List<ErpSellerStoreEmpower> empowerList = JSONObject.parseArray(JSONObject.toJSONString(storeEmpowerListByCnCode.getData()), ErpSellerStoreEmpower.class);
        List<Long> ids = empowerList.stream().map(ErpSellerStoreEmpower::getId).collect(Collectors.toList());
        List<EvaluationProductDto> evaluationProductDtoList = baseMapper
                .getEvaluationProduct(ids, shieldProductIds, maxBig, minBig);
        Iterator<EvaluationProductDto> iterator = evaluationProductDtoList.iterator();
        while (iterator.hasNext()) {
            EvaluationProductDto dto = iterator.next();
            Long productId = dto.getProductId();
            // 找到运费模板看打几折
            ErpSellerStoreProductExpand productExpand = sellerStoreProductExpandMapper.selectOne(new LambdaQueryWrapper<ErpSellerStoreProductExpand>().eq(ErpSellerStoreProductExpand::getAeProductId, productId));
            if (productExpand == null) {
                iterator.remove();
                continue;
            }
            String templateId = productExpand.getTemplateId();
            if (templateId != null) {
                R<Object> objectR = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(Long.valueOf(templateId));
                if (objectR.getCode() != 200) {
                    iterator.remove();
                    continue;
                }
                ErpSellerStorePriceTemplate sellerStorePriceTemplate = JSONObject.parseObject(JSONObject.toJSONString(objectR.getData()), ErpSellerStorePriceTemplate.class);
                if (sellerStorePriceTemplate == null) {
                    iterator.remove();
                    continue;
                }
                BigDecimal discount = sellerStorePriceTemplate.getDiscount();
                if (discount == null || dto.getProductPrice() == null) {
                    iterator.remove();
                    continue;
                }
                BigDecimal decimal = new BigDecimal(dto.getProductPrice()).multiply(BigDecimal.ONE.subtract(discount.movePointLeft(2))).setScale(2, RoundingMode.UP);
                dto.setProductPrice(decimal.toString());
            }
            // 剔除大于最大金额的商品
            if (new BigDecimal(dto.getProductPrice()).compareTo(new  BigDecimal(minBig)) > 0) {
                iterator.remove();
                continue;
            }
            // 剔除掉不符合条件的
            // 有可能前几天的刷单还没有下单，所以测评表七天内的商品也不刷
            // 找出每个商品最新的一条订单是不是 疑似测评单，是的话这个商品不刷，剔除
            Boolean isEvaluation = remoteEvaluationService.sevenDaysEvaluation(dto.getProductId());
            Boolean suspectedOrder = remoteEvaluationService.judgeSuspected(dto.getProductId(), 1L);
            if (suspectedOrder || isEvaluation) {
                iterator.remove();
                continue;
            }
        }
        if (evaluationProductDtoList.size() > 100) {
            evaluationProductDtoList = evaluationProductDtoList.subList(0, 100);
        }
        return evaluationProductDtoList;
    }
}
